package com.jc.oms.controller.zfl;

import com.alibaba.fastjson.JSONObject;
import com.jc.cds.model.CustomSupplierGoods;
import com.jc.common.util.DateTimeUtil;
import com.jc.common.util.WebUtils;
import com.jc.ds.base.service.BaseServiceException;
import com.jc.ds.model.SupplierProduct;
import com.jc.ds.model.SupplierProductPrice;
import com.jc.ds.model.SystemLogList;
import com.jc.framework.enums.LogType;
import com.jc.framework.enums.ThirdPartyParam;
import com.jc.oms.controller.BaseController;
import com.jc.service.h5.ShopService;
import com.jc.service.model.h5.H5RespModel;
import com.jc.service.suppliergoods.SupplierGoodsService;
import com.jc.service.supplierproduct.SupplierProductService;
import com.jc.service.supplierproductprice.SupplierProductPriceService;
import com.jc.service.systemloglist.SystemLogListService;
import com.jc.service.zflservice.ZflCommonUtil;
import com.jc.service.zflservice.ZflProductService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jc.service.zflservice.ZflCommonUtil.ZFLHttpUtil;

@SuppressWarnings("all")
@Controller
@RequestMapping("zflProduct")
public class ZflProductController extends BaseController {

    @RequestMapping(value = "list",method = RequestMethod.GET )
    public ModelAndView index4() {
        ModelAndView mav = new ModelAndView("/product/zfl/zflProductList");
        return mav;
    }


    @Autowired
    private ZflProductService zflProductService;
    @Autowired
    private SupplierProductService supplierProductService;
    @Autowired
    private SupplierGoodsService supplierGoodsService;
    @Autowired
    private SystemLogListService systemLogListService;
    @Autowired
    private ShopService shopService;
    @Autowired
    private SupplierProductPriceService supplierProductPriceService;


    @RequestMapping(value="/getProductList" , method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> getProductList(@RequestBody Map<String,Object> param){
        Map<String,Object> resultMap = new HashMap<>();
        SystemLogList loglist = new SystemLogList();
        try{
            if (param.get("data") == null){
                resultMap.put("code", "9999");
                resultMap.put("message", "data不能为空");
                return resultMap;
            }
            String data = param.get("data").toString();
            getLoger().debug(DateTimeUtil.getDate(DateTimeUtil.LONG_TIME_FORMAT)+"==========请求最福利产品列表的请求参数"+data);
            Map<String,Object> map = JSONObject.parseObject(data, Map.class);
            zflProductService.getProductList(map);
            resultMap.put("code", "10000");
            resultMap.put("message", "成功");
        }catch (Exception e){
            resultMap.put("code", "9999");
            resultMap.put("message", e.getLocalizedMessage());
            e.printStackTrace();
        }
        return resultMap;
    }


    @RequestMapping(value="/queryProductList" , method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> queryProductList(HttpServletRequest request){
        Map<String, Object> param = null;
        try {
            param = WebUtils.ReadAsChars(request);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        request.getParameter("offset");
        System.out.println("params===================================="+param);

        Map<String,Object> resultMap = new HashMap<>();
        SystemLogList loglist = new SystemLogList();
        try{
            if (param.get("data") == null){
                resultMap.put("code", "9999");
                resultMap.put("message", "data不能为空");
                return resultMap;
            }
            String data = param.get("data").toString();
            getLoger().debug(DateTimeUtil.getDate(DateTimeUtil.LONG_TIME_FORMAT)+"==========请求最福利产品列表的请求参数"+data);
            Map<String,Object> map = JSONObject.parseObject(data, Map.class);
            Map<String, Object> result = zflProductService.queryProductList(map);
            resultMap.put("code", "10000");
            resultMap.put("rows", result.get("goods"));
            resultMap.put("total",result.get("size"));
        }catch (Exception e){
            resultMap.put("code", "9999");
            resultMap.put("message", e.getLocalizedMessage());
            e.printStackTrace();
        }
        return resultMap;
    }

    @RequestMapping(value="/zflPushPro" , method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> zflPushPro(HttpServletRequest request){
        Map<String, Object> param = null;
        try {
            param = WebUtils.ReadAsChars(request);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Map<String,Object> resultMap = new HashMap<>();
        SystemLogList loglist = new SystemLogList();
        try{
            if (param.get("ids") == null){
                resultMap.put("code", "9999");
                resultMap.put("message", "ids不能为空");
                return resultMap;
            }
            String[] ids = param.get("ids").toString().split(",");
            getLoger().debug(DateTimeUtil.getDate(DateTimeUtil.LONG_TIME_FORMAT)+"==========请求最福利产品列表的请求参数"+ids);
            for (String id:ids) {
                System.out.println(id);
                zflProductService.productSku(new HashMap<String, Object>(){{
                    put("id",id);
                }});
            }
            resultMap.put("code", "10000");
            resultMap.put("message","success");
        }catch (Exception e){
            resultMap.put("code", "9999");
            resultMap.put("message", e.getLocalizedMessage());
            e.printStackTrace();
        }
        return resultMap;
    }


    @RequestMapping(value="/updateProNum" , method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> updateProNum(HttpServletRequest request){
        Map<String, Object> param = null;
        Map<String,Object> resultMap = new HashMap<>();
        SystemLogList loglist = new SystemLogList();
        try{
            Integer start = 0;
            Integer limit = 100;
//            map1 key goodsId map2 key proid
            List<Map<String,Map<String,Object>>> pros = new ArrayList<>();
            while (true){
                //分页查询 查100条
                List<CustomSupplierGoods> customSupplierProducts = supplierGoodsService.selectPro(start, limit);
                if (CollectionUtils.isEmpty(customSupplierProducts)){
                   break;
                }
                for (CustomSupplierGoods goods:customSupplierProducts) {
                    Map<String,Map<String,Object>> goodsMap = new HashMap<>();
                    //去查询商品详情
                    Map<String, Object> proDetail = ZflCommonUtil.getProDetail(Long.valueOf(goods.getSupplierGoodsId()));
                    //获取skus
                    List<Map<String,Object>> skuVOs = JSONObject.parseObject(proDetail.get("skuVOs").toString(), List.class);
                    //查询sku
                    SupplierProduct supplierProduct = new SupplierProduct();
                    supplierProduct.setGid(goods.getId());
                    List<SupplierProduct> supplierProducts = supplierProductService.queryAll(supplierProduct);
                    for (SupplierProduct pro:supplierProducts) {
                        //循环
                        for (Map<String,Object> sku:skuVOs) {
                            if (pro.getProductId().equals(sku.get("id").toString())){
                                //相同, 进行比较 库存
                                if(!pro.getInventoryNum().toString().equals(sku.get("stockQuantity").toString())){
                                    //不相同 , 保存进list更新
                                    goodsMap.put(String.valueOf(goods.getId()),new HashMap<String,Object>(){{
                                        put(String.valueOf(pro.getId()),sku.get("stockQuantity"));
                                    }});
                                }
                            }
                        }
                    }
                    pros.add(goodsMap);
                }
                start = start+limit;
            }
            for (Map<String,Map<String,Object>> goods:pros) {
                //更新数据库库存,并通知商城
                for (String goodsKey:goods.keySet()) {
                    Map<String, Object> sku = goods.get(goodsKey);
                    for (String skuKey:sku.keySet()) {
                        Long num = Long.valueOf(sku.get(skuKey).toString());
                        Long skuId = Long.valueOf(skuKey);
                        SupplierProduct supplierProduct = new SupplierProduct();
                        supplierProduct.setId(skuId);
                        supplierProduct.setInventoryNum(Integer.valueOf(num.toString()));
                        supplierProductService.modify(supplierProduct,false);
                        //推送到商城
                        shopService.pushInventory(skuId,num.toString());
                    }
                }
            }
            resultMap.put("code", "10000");
            resultMap.put("message","success");
        }catch (Exception e){
            resultMap.put("code", "9999");
            resultMap.put("message", e.getLocalizedMessage());
            e.printStackTrace();
        }
        return resultMap;
    }

    @RequestMapping(value="/updateProPrice" , method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> updateProPrice(HttpServletRequest request){
        Map<String, Object> param = null;
        Map<String,Object> resultMap = new HashMap<>();
        SystemLogList loglist = new SystemLogList();
        try{
            Integer start = 0;
            Integer limit = 100;
//            map1 key goodsId map2 key proid
            List<Map<String,Map<String,Object>>> pros = new ArrayList<>();
            while (true){
                //分页查询 查100条
                List<CustomSupplierGoods> customSupplierProducts = supplierGoodsService.selectPro(start, limit);
                if (CollectionUtils.isEmpty(customSupplierProducts)){
                   break;
                }
                for (CustomSupplierGoods goods:customSupplierProducts) {
                    Map<String,Map<String,Object>> goodsMap = new HashMap<>();
                    //去查询商品详情
                    Map<String, Object> proDetail = ZflCommonUtil.getProDetail(Long.valueOf(goods.getSupplierGoodsId()));
                    //获取skus
                    List<Map<String,Object>> skuVOs = JSONObject.parseObject(proDetail.get("skuVOs").toString(), List.class);
                    //查询sku
                    SupplierProduct supplierProduct = new SupplierProduct();
                    supplierProduct.setGid(goods.getId());
                    List<SupplierProduct> supplierProducts = supplierProductService.queryAll(supplierProduct);
                    for (SupplierProduct pro:supplierProducts) {
                        //查询价格
                        SupplierProductPrice supplierProductPrice = new SupplierProductPrice();
                        supplierProductPrice.setSupplierProductId(pro.getId());
                        List<SupplierProductPrice> supplierProductPrices = supplierProductPriceService.queryAll(supplierProductPrice);
                        if (CollectionUtils.isEmpty(supplierProductPrices)){
                            throw new BaseServiceException("商品价格不存在 id" + pro.getId());
                        }
                        supplierProductPrice = supplierProductPrices.get(0);
                        //循环
                        for (Map<String,Object> sku:skuVOs) {
                            if (pro.getProductId().toString().equals(sku.get("id").toString())){
                                //相同, 进行比较 价格
                                if(!supplierProductPrice.getCooperateprice().toString().equals(sku.get("price").toString())){
                                    //不相同 , 保存进list更新
                                    goodsMap.put(String.valueOf(goods.getId()),new HashMap<String,Object>(){{
                                        put(String.valueOf(pro.getId()),sku.get("price")+","+sku.get("originPrice"));
                                    }});
                                }
                            }
                        }
                    }
                    pros.add(goodsMap);
                }
                start = start+limit;
            }
            for (Map<String,Map<String,Object>> goods:pros) {
                //更新数据库价格,并通知商城
                for (String goodsKey:goods.keySet()) {
                    Map<String, Object> sku = goods.get(goodsKey);
                    for (String skuKey:sku.keySet()) {
                        Long price = Long.valueOf(sku.get(skuKey).toString().split(",")[0]);
                        Long originPrice = Long.valueOf(sku.get(skuKey).toString().split(",")[1]);
                        Long skuId = Long.valueOf(skuKey);
                        List<SupplierProductPrice> supplierProductPrices = supplierProductPriceService.queryAll(new SupplierProductPrice() {{
                            setSupplierProductId(skuId);
                        }});
                        //计算价格
                        SupplierProductPrice supplierProductPrice = zflProductService.priceCalculation(0, 0, Integer.valueOf(price.toString()), Integer.valueOf(originPrice.toString()), 0,skuId );
                        supplierProductPrice.setId(supplierProductPrices.get(0).getId());
                        supplierProductPriceService.modify(supplierProductPrice,false);
                        //推送到商城
                        H5RespModel h5RespModel = shopService.pushH5(ThirdPartyParam.UPDATE_PRO_H5.getName(), new HashMap<String, Object>() {{
                            put("skuCode",skuId);
                            put("price",supplierProductPrice.getCostPrice());
                            put("taobaoPrice",supplierProductPrice.getSaleprice());
                            put("commercePrice",supplierProductPrice.getLeve1Price());
                            put("elitesPrice",supplierProductPrice.getLeve2Price());
                            put("crownPrice",supplierProductPrice.getLeve3Price());
                            put("supremacyPrice",supplierProductPrice.getLeve4Price());
                            put("cost",supplierProductPrice.getUnionCostPrice());
                            put("parentCost",supplierProductPrice.getCostPrice());
                        }},LogType.PRO_PRICE_PUSH_SHOP);
                    }
                }
            }
            resultMap.put("code", "10000");
            resultMap.put("message","success");
        }catch (Exception e){
            resultMap.put("code", "9999");
            resultMap.put("message", e.getLocalizedMessage());
            e.printStackTrace();
        }
        return resultMap;
    }




    @RequestMapping(value = "/pushJDProduct" , method = RequestMethod.POST)
    public void pushJDProduct() throws Exception {
        Map<String,Object> map = new HashMap<>();
        map.put("mall","JD");
//        int keyword = ZflProductServiceImpl.toHash(map.get("keyword").toString());
        String s = ZFLHttpUtil("mall.category.query", "1.0", map);
        System.out.println(s);
        List bizContent = JSONObject.parseObject(JSONObject.parseObject(s, Map.class).get("bizContent").toString(), List.class);
        String bizContent1 = JSONObject.parseObject(s, Map.class).get("bizContent").toString();
        //一级目录
        List<Map<String,Object>> list = JSONObject.parseObject(bizContent1, List.class);
        List<Map<String,Object>> dataParam = new ArrayList();

        //二级目录
        for (Map<String,Object> cat:list) {
//            dataParam.add(cat);
            String catId = cat.get("catId").toString();
            List<Map<String, Object>> add = add(catId);
//            for (Map<String,Object> ad:add) {
//                String catId1 = ad.get("catId").toString();
//                List<Map<String, Object>> add1 = add(catId1);
//                dataParam.add(ad);
//                dataParam.addAll(add1);
//            }
            dataParam.addAll(add);
        }
        String data = JSONObject.toJSONString(new HashMap<String, Object>() {{
            put("data", dataParam);
        }});
//        print(data,"最福利类目列表");
        //请求获取活动商品的接口\
        for (Map<String,Object> param:dataParam) {
            Map<String,Object> paramap = new HashMap<>();
            paramap.put("mall","JD");
            paramap.put("categoryIds",new ArrayList<String>(){{
                add(param.get("catId").toString());
            }});
            paramap.put("size",50);
            String result = ZFLHttpUtil("mall.sku.activity", "1.0", paramap);

            System.out.println("======商品详情:  "+result);
            Map map1 = JSONObject.parseObject(result, Map.class);
            if ("0".equals(map1.get("resultCode").toString())){
                List<Map<String,Object>> list1 = JSONObject.parseObject(JSONObject.parseObject(JSONObject.parseObject(JSONObject.parseObject(result, Map.class).get("bizContent").toString(), List.class).get(0).toString(), Map.class).get("skus").toString(), List.class);
                for (Map<String,Object> sku:list1) {
                    zflProductService.productSku(new HashMap<String, Object>(){{
                        put("id",sku.get("id"));
                        put("make","1");
                    }});
                }
            }
        }
    }

    public List<Map<String,Object>> add(String catId) throws Exception {
        Map<String,Object> paramap = new HashMap<>();
        paramap.put("mall","JD");
        paramap.put("pid",catId);
//        int keyword = ZflProductServiceImpl.toHash(map.get("keyword").toString());
        String result = ZFLHttpUtil("mall.category.query", "1.0", paramap);
        if (JSONObject.parseObject(result, Map.class).get("bizContent") == null ){
            return new ArrayList<>();
        }
        String bizRes = JSONObject.parseObject(result, Map.class).get("bizContent").toString();
        //二级目录
        List<Map<String,Object>> listS = JSONObject.parseObject(bizRes, List.class);
        return listS;
    }
}
